/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: 
 * 系统版本: 1.0.0
 * 开发人员: zhangfb
 * 开发时间: 2019/3/30 14:39
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.hyacinth.schedule.factory;

import com.hyacinth.schedule.domian.ScheduleJobEntity;
import com.hyacinth.schedule.utils.TaskUtils;
import com.hyacinth.utils.Assert;
import com.hyacinth.utils.json.JsonMapper;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 任务job
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
public class ScheduleJob implements Job {

    private static final String WAIT = "W";
    private static final String SUCCESS = "S";
    private static final String FAILURE = "F";

    private final Logger LOGGER = LoggerFactory.getLogger(getClass());

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 获取任务执行实例
        ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap().get(ScheduleJobEntity.JOB_PARAM_KEY);
        if (scheduleJob == null) {
            throw new JobExecutionException("任务执行|获取任务执行实例失败");
        }
        // 打印任务实例详情
        LOGGER.info("任务实例详情={}", JsonMapper.toJsonString(scheduleJob));
        Long taskId = scheduleJob.getTaskId();
        Assert.notNull(taskId, "任务名称不能为空");
        String taskName = scheduleJob.getTaskName();
        Assert.notNull(taskName, "任务名称不能为空");

        // 任务开始时间
        long startTime = System.currentTimeMillis();
        // 执行耗时
        long costTime = 0;
        // 执行状态
        String exStatus = WAIT;
        // 执行信息
        String msg = "开始执行";
        try {
            LOGGER.debug("任务准备执行，任务ID：{}", taskId);
            // 执行相关实例
            TaskUtils.executeTask(taskName, scheduleJob.getParams());
            // 任务执行耗时ms
            costTime = System.currentTimeMillis() - startTime;
            exStatus = SUCCESS;
            msg = "执行成功";
            LOGGER.debug("任务执行完毕，任务ID：{}, 总共耗时：{}ms", taskId, costTime);
        } catch (Exception e) {
            costTime = System.currentTimeMillis() - startTime;
            exStatus = FAILURE;
            msg = "执行失败-"+e.getMessage();
            LOGGER.error("任务执行失败，任务ID：{}", taskId, e);
        } finally {
            // 记录日志
            saveLog(taskId, taskName, costTime, exStatus, msg);
        }
    }

    /**
     * 保存执行日志
     *
     * @param taskId   任务id
     * @param taskName 任务名称
     * @param costTime 执行耗时
     * @param exStatus 执行状态
     * @param msg      执行详细信息
     * @throws JobExecutionException job执行异常
     */
    protected void saveLog(Long taskId, String taskName, Long costTime, String exStatus, String msg) throws JobExecutionException {

    }
}
